package user

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type SearchVipLevelInfosLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 会员VIP等级信息 - 查询
func NewSearchVipLevelInfosLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchVipLevelInfosLogic {
	return &SearchVipLevelInfosLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SearchVipLevelInfosLogic) SearchVipLevelInfos(req *types.SearchVipLevelInfosRequest) (resp *types.SearchVipLevelInfosResponse, err error) {
	// 从 rpc 服务器获取到数据
	rpcResp, err := l.svcCtx.UserServiceRPC.UserSearchVipLevelInfos(l.ctx, nil)
	if err != nil {
		logc.Error(l.ctx, "Call SearchVipLevelInfos error: %v", err)
		return &types.SearchVipLevelInfosResponse{
			VipLevelInfosList: make([]*types.VipLevelInfos, 0),
		}, nil
	}

	// 解析、组合数据
	infosList := make([]*types.VipLevelInfos, len(rpcResp.VipLevelInfosList))

	for i, info := range rpcResp.VipLevelInfosList {

		// 组装返利率数据结构体
		rebateRateList := make([]*types.RebateRate, len(info.RebateRateList))
		for j, rebateRate := range info.RebateRateList {
			rebateRateList[j] = &types.RebateRate{
				RebateRateId: rebateRate.RebateRateId,
				TypeName:     rebateRate.TypeName,
				Name:         rebateRate.Name,
				Value:        rebateRate.Value,
			}
		}

		upgradeAward, monthlyAward := &AwardConfig{}, &AwardConfig{}

		err = json.Unmarshal([]byte(info.UpgradeAward), upgradeAward)
		if err != nil {
			logc.Error(l.ctx, "Call SearchVipLevelInfos error: %v", err)
			return nil, err
		}

		err = json.Unmarshal([]byte(info.MonthlyAward), monthlyAward)
		if err != nil {
			logc.Error(l.ctx, "Call SearchVipLevelInfos error: %v", err)
			return nil, err
		}

		// 组装会员等级信息结构体
		infosList[i] = &types.VipLevelInfos{
			VipLevelId:   info.VipLevelId,   // VIP等级ID
			VipLevelName: info.VipLevelName, // VIP等级名称
			UpgradeExp:   info.UpgradeExp,   // 升级条件（Exp）
			KeepGradeExp: info.KeepGradeExp, // 保级条件（Exp）
			DiscountExp:  info.DiscountExp,  // 扣除经验（Exp）

			UpgradePointAward:   upgradeAward.Point, // 升级积分奖励
			UpgradeBalanceAward: upgradeAward.Money, // 升级余额奖励
			MonthlyPointAward:   monthlyAward.Point, // 月积分奖励
			MonthlyBalanceAward: monthlyAward.Money, // 月余额奖励

			RechargeAward:  info.RechargeAward, // 充值奖励
			SafeDailyRate:  info.SafeDailyRate, // 保险箱日利率（%）
			RebateRateList: rebateRateList,
		}
	}

	// 组装返回信息结构体
	resp = &types.SearchVipLevelInfosResponse{
		VipLevelInfosList: infosList,
	}

	return
}

// 奖励配置结构体
type AwardConfig struct {
	Point int32 `json:"point" form:"point"` // 积分奖励
	Money int32 `json:"money" form:"money"` // 余额奖励
}
